﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CloudClass.Models;
using CloudClass.Services;
using CloudClass.ViewModels;
using Orchard;
using Orchard.DisplayManagement;
using Orchard.DisplayManagement.Shapes;
using Orchard.Localization;
using Orchard.Logging;
using Orchard.Themes;
using Orchard.UI.Navigation;

namespace CloudClass.Controllers
{
    public class ClassController : Controller
    {
        public IOrchardServices Services { get; set; }
        private readonly ICourseInfoService _courseInfoService;
        private readonly ICourseClassifyService _courseClassifyService;
        private readonly ICloudClassAuthService _cloudClassAuthService;
        private readonly ILessonService _lessonService;
        private readonly IMyCourseService _myCourseService;
        private readonly IAskService _askService;
        private readonly IAskVoteService _askVoteService;
        private readonly IAnswerService _answerService;
        private readonly IEvaluationService _evaluationService;
        private readonly INotesService _notesService;
        private readonly ICommentService _commentService;
        private readonly ICollectionService _collectionService;
        private readonly ICommentReplyService _commentReplyService;
        private readonly ITalkService _talkService;
        private readonly ITopNotesService _topNotesService;

        public ILogger Logger { get; set; }
        public Localizer T { get; set; }
        public dynamic Shape { get; set; }

        public ClassController(IOrchardServices services,
            ICourseInfoService courseInfoService,
            ICourseClassifyService courseClassifyService,
            IShapeFactory shapeFactory,
            ICloudClassAuthService cloudClassAuthService,
            ILessonService lessonService,
            IMyCourseService myCourseService,
            IAskService askService,
            IAskVoteService askVoteService,
            IAnswerService answerService,
            IEvaluationService evaluationService,
            INotesService notesService,
            ICommentService commentService,
            ICommentReplyService commentReplyService,
            ICollectionService collectionService,
            ITalkService talkService,
            ITopNotesService topNotesService
            )
        {
            Services = services;
            _cloudClassAuthService = cloudClassAuthService;
            _courseInfoService = courseInfoService;
            _courseClassifyService = courseClassifyService;
            T = NullLocalizer.Instance;
            Shape = shapeFactory;
            _lessonService = lessonService;
            _myCourseService = myCourseService;
            _askService = askService;
            _askVoteService = askVoteService;
            _answerService = answerService;
            _evaluationService = evaluationService;
            _notesService = notesService;
            _commentService = commentService;
            _commentReplyService = commentReplyService;
            _collectionService = collectionService;
            _talkService = talkService;
            _topNotesService = topNotesService;
            Logger = NullLogger.Instance;
        }


        [Themed]
        public ActionResult Index()
        {
            List<CourseClassify> courseClassifies =
                _courseClassifyService.GetList().Where(p => p.ParentId == 0).ToList();
            List<CourseClassify> subCourseClassifies = _courseClassifyService.GetList();

            UserInfo userinfo = _cloudClassAuthService.GetAuthenticatedUser();
            return View("Index", new ClassIndexCatelog
            {
                CourseClassifies = courseClassifies,
                SubCourseClassifies = subCourseClassifies,
                UserInfo = userinfo
            });
        }

        /// <summary>
        /// 获取课程列表
        /// </summary>
        /// <returns></returns>
        public JsonResult GetClassInfo(int pagesize, int currentpage, int free, int catelog, int neworhot)
        {
            List<CourseInfo> courseInfos = _courseInfoService.GetList();

            //筛选是否免费
            if (free == 1)
            {
                courseInfos = courseInfos.Where(p => p.Money == 0).ToList();
            }
            else if (free == 2)
            {
                courseInfos = courseInfos.Where(p => p.Money != 0).ToList();
            }

            //类别
            if (catelog != 0)
            {
                courseInfos = courseInfos.Where(p => p.CourseClassify.Id == catelog).ToList();
            }

            //是否最新排序
            if (neworhot == 0)
            {
                //最新
                courseInfos = courseInfos.OrderByDescending(p => p.UpdateTime).ToList();
            }
            else
            {
                //最热
                courseInfos = courseInfos.OrderByDescending(p => p.CreateTime).ToList();
            }

            int totalCount = courseInfos.Count();

            courseInfos = courseInfos.Skip((currentpage - 1)*pagesize).Take(pagesize).ToList();

            return Json(new ClassListPage
            {
                CourseInfos = courseInfos,
                Count = totalCount
            }, JsonRequestBehavior.AllowGet);

        }

        /// <summary>
        /// 课程详细页
        /// </summary>
        /// <param name="id">课程编号</param>
        /// <returns></returns>
        [Themed]
        public ActionResult ClassPage(int id)
        {
            CourseInfoDetail courseInfoDetail = new CourseInfoDetail();
            //课程详情
            courseInfoDetail .CourseInfo= _courseInfoService.Get(id);
            if (courseInfoDetail.CourseInfo.PublisherType == 1)
            {
                courseInfoDetail.Publisher = courseInfoDetail.CourseInfo.PublisherUserInfo.UserName;
                courseInfoDetail.ImgUrl = courseInfoDetail.CourseInfo.PublisherUserInfo.UserPhoto;
                courseInfoDetail.PublisherDesc = courseInfoDetail.CourseInfo.PublisherUserInfo.UserDesc;
            }
            else
            {

                courseInfoDetail.Publisher = courseInfoDetail.CourseInfo.Mechanism.MechanismName;
                courseInfoDetail.ImgUrl = courseInfoDetail.CourseInfo.Mechanism.MechanismImage;
                courseInfoDetail.PublisherDesc = courseInfoDetail.CourseInfo.Mechanism.MechanismIntroduction;
            }
            //课时列表
            courseInfoDetail.LessonList = _lessonService.GetListByCourseId(id).OrderBy(p=>p.ChapterOrder).ToList();
            //学习该课程的人
            courseInfoDetail.UserInfoList =
                _myCourseService.GetList().Where(p => p.CourseInfo.Id == id).ToList().Select(p => p.UserInfo).ToList();

            //转换问答列表
            var list = _askService.GetList().Take(5).ToList();
            List<AskAbout> newList = new List<AskAbout>();
            foreach (var ask in list)
            {
                AskAbout askAbout = new AskAbout();
                askAbout.Ask = ask;
                askAbout.AnswerCount = _answerService.GetList().Where(p => p.Ask.Id == ask.Id).ToList().Count;
                askAbout.VoteCount = _askVoteService.GetList().Where(p => p.Ask.Id == ask.Id).ToList().Count;
                newList.Add(askAbout);
            }
            courseInfoDetail.AskList = newList;

            //评价列表
            courseInfoDetail.EvaluationList =
                _evaluationService.GetList().Where(p => p.CourseInfo.Id == id).Take(5).ToList();

            //判断是否加入课程
            UserInfo user=_cloudClassAuthService.GetAuthenticatedUser();
            if (user == null)
            {
                courseInfoDetail.IsJoin = 0;
            }
            else
            {
                if (
                    _myCourseService.GetList()
                        .Where(p => p.CourseInfo.Id == id && p.UserInfo.Id == user.Id)
                        .ToList()
                        .Count > 0)
                {
                    courseInfoDetail.IsJoin = 1;
                }
                else
                {
                    courseInfoDetail.IsJoin = 0;
                }
            }
            

            return View("ClassPage", courseInfoDetail);
        }

        /// <summary>
        /// 加入课程
        /// </summary>
        /// <param name="courseId"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult JoinClass(int courseId)
        {
            MyCourse myCourse = new MyCourse();
            myCourse.UserInfo = _cloudClassAuthService.GetAuthenticatedUser();
            myCourse.CourseInfo = _courseInfoService.Get(courseId);
            myCourse.JoinCourseTime = System.DateTime.Now;
            myCourse.StudyTime = System.DateTime.Now;
            if (_myCourseService.Create(myCourse))
            {
                return Json("success");
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 评价课程
        /// </summary>
        /// <param name="courseId"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        [HttpPost]
        public JsonResult EvalClass(int courseId, string text)
        {
            Evaluation model = new Evaluation();
            model.CourseInfo = _courseInfoService.Get(courseId);
            model.EvaluationLevel = 5;
            model.EvaluationTime=System.DateTime.Now;
            model.EvaluationType = 1;
            model.EvaluationContent = text;
            model.UserInfo = _cloudClassAuthService.GetAuthenticatedUser();
            if (_evaluationService.Create(model))
            {
                return Json("success");
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        ///  笔记列表
        /// </summary>
        /// <param name="courseId"></param>
        /// <returns></returns>
        [Themed]
        public ActionResult Note(int id, PagerParameters pagerParameters, int LessonID=0)
        {
            Pager pager = new Pager(Services.WorkContext.CurrentSite, pagerParameters);
            List<Notes> notesList;
            if (LessonID == 0)
            {
                notesList =
                    _notesService.GetList()
                        .OrderByDescending(p => p.PublishTime)
                        .ToList();
            }
            else
            {
                notesList =
                    _notesService.GetList()
                        .Where(p => p.Lesson.Id == LessonID)
                        .OrderByDescending(p => p.PublishTime)
                        .ToList();
            }
            NotesViewModel viewModel = new NotesViewModel();
            viewModel.CourseInfo = _courseInfoService.Get(id);
            //var notesList = _notesService.GetList().Where(p=>p.Lesson.Id==lessonId).OrderByDescending(p => p.PublishTime).ToList();

            List<NotesAbout> notesAbouts = new List<NotesAbout>();
            foreach (var notes in notesList)
            {
                NotesAbout model = new NotesAbout();
                model.Notes = notes;
                model.CollectCount =
                    _collectionService.GetList().Where(p => p.CollectionType == 1 && p.Notes == notes).Count();
                model.CommentCount = _commentService.GetList().Where(p => p.Notes == notes).Count();
                model.TopCount = _topNotesService.GetList().Where(p => p.Notes == notes).Count();
                notesAbouts.Add(model);
            }
            viewModel.NotesAboutList = notesAbouts;
            //课程详情
            viewModel.CourseInfo = _courseInfoService.Get(id);

            viewModel.LessonList = _lessonService.GetList().Where(p => p.CourseInfo == viewModel.CourseInfo).ToList();

            int totalItemCount = viewModel.NotesAboutList.Count();

            if (pager.PageSize != 0)
            {
                viewModel.NotesAboutList = viewModel.NotesAboutList.Skip((pager.Page - 1) * pager.PageSize).Take(pager.PageSize).ToList();
            }


            if (viewModel.CourseInfo.PublisherType == 1)
            {
                viewModel.Publisher = viewModel.CourseInfo.PublisherUserInfo.UserName;
                viewModel.ImgUrl = viewModel.CourseInfo.PublisherUserInfo.UserPhoto;
                viewModel.PublisherDesc = viewModel.CourseInfo.PublisherUserInfo.UserDesc;
            }
            else
            {

                viewModel.Publisher = viewModel.CourseInfo.Mechanism.MechanismName;
                viewModel.ImgUrl = viewModel.CourseInfo.Mechanism.MechanismImage;
                viewModel.PublisherDesc = viewModel.CourseInfo.Mechanism.MechanismIntroduction;
            }
            viewModel.LessonID = LessonID;
            viewModel.Pager = Shape.Pager(pager).TotalItemCount(totalItemCount);
            return View("Note", viewModel);

        }

        [Themed]
        public ActionResult Talk()
        {
            return View("Talk");
        }

        [Themed]
        public ActionResult Question()
        {

            return View("Question");
        }

        [Themed]
        public ActionResult AddNote(int id)
        {
            if (_cloudClassAuthService.GetAuthenticatedUser() == null)
            {
                return RedirectToAction("Register", "Home");
            }
            
            AddNoteLessonList lessonList = new AddNoteLessonList();
            lessonList.lessons = _lessonService.GetListByCourseId(id);
            lessonList.CourseInfo = _courseInfoService.Get(id);
            return View("AddNote", lessonList);
        }

        /// <summary>
        /// 写笔记
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public JsonResult CreateNote(int lessonId, string noteContent, bool isPrivate, int courseId)
        {
            try
            {
               
                Notes model = new Notes();
                model.CourseInfo = _courseInfoService.Get(courseId);
                model.Lesson = _lessonService.Get(lessonId);
                model.NotesContent = noteContent;
                if (isPrivate == false)
                    model.NotesType = 1;
                else
                    model.NotesType = 2;
                model.PublishTime = System.DateTime.Now;
                model.UserInfo = _cloudClassAuthService.GetAuthenticatedUser();
                _notesService.Create(model);
                return Json("success");
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.Error, ex,"",null);
                return null;
            }
          
           
        }
    }
}